from Infrastructure.ConstValues import DEFAULT_PAGE_SIZE
from sqlalchemy.sql.expression import true
from UserManageDao import UserManageDao
from UIComponents.PageNavigator import PageNavigator
from typing import Optional
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QComboBox, QHBoxLayout, QHeaderView, QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget
from PySide6.QtCore import Qt
from AssetManageService import AssetManageService
from math import ceil

class AssetManageTab(QWidget):
    def __init__(self, parent: Optional[QWidget] = None, f: Qt.WindowFlags = Qt.Tool) -> None:
        super().__init__(parent=parent, f=f)
        if not self.objectName():
            self.setObjectName(u"AssetManageTab")
        self.groupInited = False
        self.userInited = False
        vlayout = QVBoxLayout(self)
        hlayout = QHBoxLayout()
        self.cbxGroups = QComboBox()
        self.cbxGroups.setObjectName(u"cbxGroups")
        hlayout.addWidget(self.cbxGroups)
        self.cbxUsers = QComboBox()
        self.cbxUsers.setObjectName(u"cbxUsers")
        hlayout.addWidget(self.cbxUsers)
        self.buttonRefresh = QPushButton("刷新")
        hlayout.addWidget(self.buttonRefresh)
        vlayout.addLayout(hlayout)
        self.tabAssets = QTableWidget()
        self.tabAssets.setObjectName(u"tabAssets")
        vlayout.addWidget(self.tabAssets)
        self.pageNavigator = PageNavigator(3)
        vlayout.addWidget(self.pageNavigator)
        self.init_group_cbx()
        self.init_user_cbx()
        self.pageNavigator.currentPageChanged.connect(self.update_table)
        self.buttonRefresh.clicked.connect(self.buttonRefreshClicked)
        self.update_table(1)

    def init_group_cbx(self):
        groups = UserManageDao.get_groups()
        if self.groupInited:
            self.cbxGroups.currentIndexChanged.disconnect(self.cbx_groups_index_changed)
        self.cbxGroups.clear()
        self.cbxGroups.addItem('全部',None)
        for group in groups:
            self.cbxGroups.addItem(group["group"])
        self.cbxGroups.currentIndexChanged.connect(self.cbx_groups_index_changed)
        self.groupInited = true

    def init_user_cbx(self,):
        if self.userInited:
            self.cbxUsers.currentIndexChanged.disconnect(self.cbx_users_index_changed)
        self.cbxUsers.clear()
        self.cbxUsers.addItem('全部', None)
        users = UserManageDao.get_all_user()
        for user in users:
            self.cbxUsers.addItem(user.name,user)
        self.cbxUsers.currentIndexChanged.connect(self.cbx_users_index_changed)
        self.userInited = True

    def cbx_groups_index_changed(self):
        self.update_user_cbx()
        self.update_table(1)

    def cbx_users_index_changed(self):
        self.update_table(1)

    def update_user_cbx(self):
        group = self.cbxGroups.currentText()
        if group == '全部':
            users = UserManageDao.get_all_user()
        else:
            users = UserManageDao.search_user(group=group)
        self.cbxUsers.clear()
        self.cbxUsers.addItem('全部',None)
        for user in users:
            self.cbxUsers.addItem(user.name,user)

    def update_table(self, pageIndex):
        self.tabAssets.clear()
        self.tabAssets.setRowCount(0)
        group = self.cbxGroups.currentText()
        user = self.cbxUsers.currentData()
        kwargs = {}
        if group != '全部':
            kwargs["group"] = group
        if user != None:
            kwargs["uuid"] = user.uuid
        args = []
        args.append({})
        args.append(kwargs)
        result = AssetManageService.get_user_device_page(args, True, pageIndex, DEFAULT_PAGE_SIZE)
        count = result[0]
        assets = result[1]
        self.tabAssets.horizontalHeader().setFixedHeight(50)  ##设置表头高度
        self.tabAssets.setHorizontalHeaderLabels(['id','姓名','年龄','学号','地址'])#设置表头文字
        self.tabAssets.setSelectionMode(QAbstractItemView.ExtendedSelection)  # 设置只可以单选，可以使用ExtendedSelection进行多选
        self.tabAssets.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置 不可选择单个单元格，只可选择一行。
        self.tabAssets.setColumnCount(16)  ##设置表格一共有五列
        self.tabAssets.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.tabAssets.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tabAssets.setHorizontalHeaderLabels(
            ['选择','设备类别', '资产编号', '设备编号','品牌', '设备型号', '使用类型','产地',
             '使用状态','用途','生产日期','使用位置','使用人','部门','办公室','备注'])  # 设置表头文字

        row = self.tabAssets.rowCount()

        for item in assets:
            self.tabAssets.setRowCount(row + 1)
            ##下面六行用于生成居中的checkbox，不知道有没有别的好方法
            ck = QCheckBox()
            h = QHBoxLayout()
            h.setAlignment(Qt.AlignCenter)
            h.addWidget(ck)
            w = QWidget()
            w.setLayout(h)

            self.tabAssets.setCellWidget(row, 0, w)
            self.tabAssets.setItem(row, 1, QTableWidgetItem(item[0].device_category))
            self.tabAssets.setItem(row, 2, QTableWidgetItem(item[0].asset_ID))
            self.tabAssets.setItem(row, 3, QTableWidgetItem(item[0].device_ID))
            self.tabAssets.setItem(row, 4, QTableWidgetItem(item[0].brand))
            self.tabAssets.setItem(row, 5, QTableWidgetItem(item[0].device_model))
            self.tabAssets.setItem(row, 6, QTableWidgetItem(item[0].using_type))
            self.tabAssets.setItem(row, 7, QTableWidgetItem(item[0].origin))
            self.tabAssets.setItem(row, 8, QTableWidgetItem(str(item[0].status)))
            self.tabAssets.setItem(row, 9, QTableWidgetItem(item[0].application))
            self.tabAssets.setItem(row, 10, QTableWidgetItem(item[0].production_date.strftime('%Y-%m-%d')))
            self.tabAssets.setItem(row, 11, QTableWidgetItem(item[0].using_locate))
            if item[1] is not None:
                self.tabAssets.setItem(row, 12, QTableWidgetItem(item[1].name))
                self.tabAssets.setItem(row, 13, QTableWidgetItem(item[1].group))
                self.tabAssets.setItem(row, 14, QTableWidgetItem(item[1].location))
            self.tabAssets.setItem(row, 15, QTableWidgetItem(item[0].remarks))

            row +=1

        self.pageNavigator.setMaxPage(ceil(count * 1.0 / DEFAULT_PAGE_SIZE))
        self.pageNavigator.setCurrentPage(pageIndex)

    def buttonRefreshClicked(self):
        self.init_group_cbx()
        self.init_user_cbx()
        self.update_table(1)